function[class] = kNNClassification(image, k, collectedData, idClassMapping, ignoreNr)
% Classifies the given image using k-NN on extracted features.
%
%   INPUT
%   image...........an image in binary format
%   k...............the number of nearest neighbours regarded by the
%                   algorithm
%   collectedData...the 'knowledge' of the k-NN algorithm; might be created
%                   previously with trainForKNN
%   idClassMapping..a cell array containing the mapping from the id to the
%                   classname where the id is the position of the classname
%                   string in the array
%   ignoreNr........the index of the training data that shall be omitted
%                   during classification; set to zero to use all training
%                   data
%   OUTPUT
%   class...........the classification for the given image as a string

    features = calculateFeatures(image);
    
    % calculate the difference between the feature vector of the given image
    % and the feature vectors in the training dataset
    difference = collectedData(:, 2:end) - ones(size(collectedData, 1), 1) * features;
    % square the difference in every dimension and sum the results (our k-NN
    % uses the euclidean distance); no need for taking the square-root since
    % it would not affect the sorting order.
    distance = sum(difference .^ 2, 2);
    [notNeeded, indizes] = sort(distance);
    % indizes now contains the IDs of training data vectors in the order of
    % increasing distance from the given image's feature vector; now remove
    % the ID that was passed as parameter to this function
    indizes = indizes(indizes ~= ignoreNr);
    % choose the class that occurs mostly within the first (nearest) k
    % vectors and return it
    classID = mode(collectedData(indizes(1:k),1));
    class = idClassMapping{classID};
end
